package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dto.DataManager;

/**
 * Servlet implementation class GetProducts
 */
@WebServlet("/GetProducts")
public class GetProducts extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public GetProducts() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		DataManager dataManager = new DataManager();
		StringBuffer sbuff = new StringBuffer();

		String mode = request.getParameter("mode");

		if (mode.equalsIgnoreCase("getproduct")) {
			int categoryId = Integer
					.valueOf(request.getParameter("categoryId"));
			int producerId = Integer
					.valueOf(request.getParameter("producerId"));

			int producerOwnCategoryId = dataManager.isHaveProducerOwnCategory(
					producerId, categoryId);
			System.out.println(categoryId + " " + producerId + " " + producerOwnCategoryId);
			
			List<String> productNames = new ArrayList<String>();
			List<Integer> productIds = new ArrayList<Integer>();
			dataManager.getProductByProducerOwnCategoryId(
					producerOwnCategoryId, productIds, productNames);

			sbuff.append("<option value=\"-1\">...</option>");

			request.setCharacterEncoding("UTF-8");
			response.setContentType("text/html;charset=UTF-8");

			for (int i = 0; i < productNames.size(); ++i) {
				sbuff.append("<option value=\"" + productIds.get(i) + "\">");
				sbuff.append(productNames.get(i));
				sbuff.append("</option>");
			}
		}
		
		else if(mode.equalsIgnoreCase("getprice")) {
			int productId = Integer.valueOf(request.getParameter("productId"));
			
			sbuff.append(dataManager.getProductById(productId).getPrice());
		}

		PrintWriter pw = response.getWriter();
		pw.print(sbuff.toString());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
